import React, { useState, useEffect, useRef } from 'react';
import { Table, Button, Space, Input, Select, Modal, Form, message, Tag} from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import axios from 'axios';
import './AdminUserPage.css';

const { Option } = Select;
const { confirm } = Modal;

const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({});
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });

  // 模态框状态
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editUser, setEditUser] = useState(null);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [changePasswordModalVisible, setChangePasswordModalVisible] = useState(false);

  const fetchUsers = async (params = {}) => {
    setLoading(true);
    try {
      const response = await axios.post('http://127.0.0.1:8080/adminUser/search', params);
      var data = response.data;
      console.log(data);
      setUsers(data.data.content);
      setPagination({ ...pagination, total: response.data.data.totalElements });
    } catch (error) {
      console.error('Error fetching users:', error);
    } finally {
      setLoading(false);
    }
  };

//  useEffect(() => {
//    fetchUsers({ ...searchParams, ...pagination });
//  }, [searchParams, pagination]);

useEffect(() => {
    fetchUsers({ ...searchParams, ...pagination });
  }, [searchParams]);

  const handleTableChange = (pagination) => {
    setSearchParams({ ...searchParams, ...pagination });
  };

  const handleSearch = (values) => {
    setSearchParams(values);
  };

  const columns = [
    {
      title: '登录名',
      dataIndex: 'loginName',
      key: 'loginName',
    },
    {
      title: '显示名称',
      dataIndex: 'showName',
      key: 'showName',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => <Tag color={status.name === 'ENABLED' ? 'green' : 'red'}>{status.desc}</Tag>,
    },
    {
      title: '操作',
      key: 'action',
      render: (record) => (
        <Space size="middle">
          <a disabled={record.status.name === 'ENABLED'} onClick={() => handleStatusChange(record, 'enable')}>启用</a>
          <a disabled={record.status.name === 'DISABLED'} onClick={() => handleStatusChange(record, 'disable')}>禁用</a>
          <a onClick={() => handleEditClick(record)}>编辑</a>
          <a onClick={() => handlePasswordChangeClick(record)}>修改密码</a>
        </Space>
      ),
    },
  ];

  const handleStatusChange = async (record, action) => {
    try {
      let command = {};
      if (action === 'enable') {
        command = { id: record.id };
        await axios.post('http://127.0.0.1:8080/adminUser/enable', { id: record.id });
      } else if (action === 'disable') {
        command = { id: record.id };
        await axios.post('http://127.0.0.1:8080/adminUser/disable', { id: record.id });
      }

      message.success(`用户状态修改成功`);
      fetchUsers({ ...searchParams, ...pagination });
    } catch (error) {
      console.error('Error changing user status:', error);
      message.error('更改用户状态失败');
    }
  };

  const handleEditClick = (record) => {
    setEditUser(record);
    setEditModalVisible(true);
  };

  const handlePasswordChangeClick = (record) => {
    setEditUser(record);
    setChangePasswordModalVisible(true);
  };

  const handleCreateClick = () => {
    setCreateModalVisible(true);
  };

  // 添加表单引用
  const editFormRef = useRef(null);
  const changePasswordFormRef = useRef(null);
  const createFormRef = useRef(null);

  const EditForm = () => (
    <Form
      ref={editFormRef} // 添加表单引用
      name="editUser"
      initialValues={{ showName: editUser.showName }}
      onFinish={async (values) => {
        try {
          await axios.post('http://127.0.0.1:8080/adminUser/update', { id: editUser.id, showName: values.showName });
          message.success('用户信息已更新');
          setEditModalVisible(false);
          fetchUsers({ ...searchParams, ...pagination });
        } catch (error) {
          console.error('Error updating user:', error);
          message.error('更新用户信息失败');
        }
      }}
    >
      <Form.Item label="显示名称" name="showName" rules={[{ required: true, message: '请输入显示名称!' }]}>
        <Input />
      </Form.Item>
    </Form>
  );

  const ChangePasswordForm = () => (
    <Form
      ref={changePasswordFormRef}
      name="changePassword"
      initialValues={{ password: '', newPassword: '' }}
      onFinish={async (values) => {
        try {
          await axios.post('http://127.0.0.1:8080/adminUser/changePassword', { id: editUser.id, password: values.password, newPassword: values.newPassword });
          message.success('密码已更新');
          setChangePasswordModalVisible(false);
          fetchUsers({ ...searchParams, ...pagination });
        } catch (error) {
          console.error('Error changing password:', error);
          message.error('更新密码失败');
        }
      }}
    >
      <Form.Item label="旧密码" name="password" rules={[{ required: true, message: '请输入旧密码!' }]}>
        <Input.Password />
      </Form.Item>

      <Form.Item label="新密码" name="newPassword" rules={[{ required: true, message: '请输入新密码!' }]}>
        <Input.Password />
      </Form.Item>
    </Form>
  );

  const CreateForm = () => (
    <Form
      ref={createFormRef}
      name="createUser"
      initialValues={{ loginName: '', showName: '', password: '' }}
      onFinish={async (values) => {
        try {
          await axios.post('http://127.0.0.1:8080/adminUser/create', { loginName: values.loginName, showName: values.showName, loginPassword: values.password });
          message.success('用户已创建');
          setCreateModalVisible(false);
          fetchUsers({ ...searchParams, ...pagination });
        } catch (error) {
          console.error('Error creating user:', error);
          message.error('创建用户失败');
        }
      }}
    >
      <Form.Item label="登录名" name="loginName" rules={[{ required: true, message: '请输入登录名!' }]}>
        <Input />
      </Form.Item>

      <Form.Item label="显示名称" name="showName" rules={[{ required: true, message: '请输入显示名称!' }]}>
        <Input />
      </Form.Item>

      <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码!' }]}>
        <Input.Password />
      </Form.Item>
    </Form>
  );

  return (
     <div className="admin-user-page">
      <Form
        name="searchForm"
        layout="inline"
        onFinish={handleSearch}
        className="search-form"
      >
        <Form.Item label="登录名" name="loginName">
          <Input placeholder="请输入登录名" />
        </Form.Item>
        <Form.Item label="状态" name="status">
          <Select placeholder="请选择">
            <Option value="" selected>全部</Option>
            <Option value="ENABLED">启用</Option>
            <Option value="DISABLED">禁用</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={handleCreateClick} icon={<PlusOutlined />}>
            创建用户
          </Button>
        </Form.Item>
      </Form>

    <div className="table-container">
      <Table
        rowKey="id"
        columns={columns}
        dataSource={users}
        loading={loading}
        pagination={pagination}
        onChange={handleTableChange}
      />
    </div>
      <Modal
        title="编辑用户"
        visible={editModalVisible}
        onOk={() => {
                editFormRef.current?.submit();
                setEditModalVisible(false);
            }
        }
        onCancel={() => setEditModalVisible(false)}
      >
        <EditForm />
      </Modal>

      <Modal
        title="修改密码"
        visible={changePasswordModalVisible}
        onOk={() => {
                changePasswordFormRef.current?.submit();
                setChangePasswordModalVisible(false);
            }
        }
        onCancel={() => setChangePasswordModalVisible(false)}
      >
        <ChangePasswordForm />
      </Modal>

      <Modal
        title="创建用户"
        visible={createModalVisible}
        onOk={() => {
                createFormRef.current?.submit();
                setCreateModalVisible(false)
            }
        }
        onCancel={() => setCreateModalVisible(false)}
      >
        <CreateForm />
      </Modal>
    </div>
  );
};

export default UserManagement;
